import { Context, Schema, h } from 'koishi'

import {} from 'koishi-plugin-puppeteer'

import {} from 'koishi-plugin-assets-local'

export const inject = ['database', 'server'] // 注入插件

export const name = 'blue'

export interface Config {}

export const Config: Schema<Config> = Schema.object({})

import { 
  tens,
  jin,
  more,
  format,
  updateConfig,
} from "./utils/utils";

import getConfig from "./utils/config.json";

declare module 'koishi' { // 扩展表
  interface Tables {
    blueUserInfo: {
      id: string,
      list: Array<any>,
      stone: number,
      targetStone: number,
    },
  }
}

export function apply(ctx: Context) {

  ctx.model.extend('blueUserInfo', { // 扩展表
    id: {
      type: 'string',
      nullable: true,
      initial: '0',
    },
    list: { // 抽卡记录
      type: 'object',
      nullable: true,
      initial: [],
    },
    stone: {
      type: 'unsigned',
      nullable: true,
      initial: 0,
    },
    targetStone: {
      type: 'unsigned',
      nullable: true,
      initial: 0,
    }
  })
  
  ctx.on('message', async (session: any) => {

    let { content, event } = session

    let isAt = false
    let targetUserId = session.event.user.id // 信息源用户id

    let { user } = event

    // 去除两端空格
    content = content.trim()

    if (content == '十连') {
      const userInfo = await ctx.database.get('blueUserInfo', user.id)
      let list = []
      if (userInfo.length) list = userInfo[0].list
      else {
        const registerUser = {
          id: user.id,
          list: []
        }
        await ctx.database.create('blueUserInfo', registerUser)
      }
      const stone = userInfo[0].targetStone
      if (stone < 1200) return session.send('青辉石不够了喵~\n可输入指令\n「 重置青辉石 」: 将青辉石重置为初始状态\n「 青辉石 」: 设置初始青辉石数量')
      const result = tens()
      result.card.map(i => {
        const hasIndex = list.findIndex(j => j.id == i.id)
        if (hasIndex > -1) list[hasIndex].num = list[hasIndex].num + i.num
        else list.push(i)
      })
      let text = format(result, list)
      text += `\n当前剩余青辉石：${stone - 1200}`
      session.send(text)
      await ctx.database.set('blueUserInfo', user.id, { list, targetStone: stone - 1200 })
    }

    if (content == '一井' || content.indexOf(`summary="[抽到了]"`) != -1) {
      const result = jin()
      let text = format(result)
      session.send(text)
    }

    if (content == '重置抽卡') {
      await ctx.database.set('blueUserInfo', user.id, { list: [] })
      session.send('已重置喵')
    }

    if (content == '重置青辉石') {
      const userInfo = await ctx.database.get('blueUserInfo', user.id)
      const stone = userInfo[0].stone
      await ctx.database.set('blueUserInfo', user.id, { targetStone: stone })
      session.send('已重置喵')
    }

    if (content == '青辉石') {
      session.send('请输入青辉石数量')
      const stone = await session.prompt()
      let isNumber = /^[0-9]+$/.test(stone as any)
      if (!isNumber) return session.send('请输入青辉石的数量喵~')
      await ctx.database.set('blueUserInfo', user.id, { stone: parseInt(stone), targetStone: parseInt(stone) })
      session.send('设置成功喵~\n当前青辉石数量：' + stone)
    }

    if (content == '统计') {
      const result = more()
      let colours = result.info.colours + result.info.up
      let coloursP = Math.round(colours / result.info.all * 10000) / 100
      const text = `统计结果：\n统计次数：${result.info.all}\n彩数：${colours}\n彩率：${coloursP}%`
      session.send(text)
    }

    // 关键词 允许后方添加参数 非简易指令
    let keyword = {
      changeUp: ['换池'],
    }
    let hasKeyWork = '' // 指令识别 用于判断需要触发的函数
    let hasKeyWorkParams = '' // 指令后续参数
    let actionKeyWork = '' // 触发的文字
    for (const key in keyword) {
      if (Object.prototype.hasOwnProperty.call(keyword, key)) {
        const item = keyword[key]
        // 支持以/为前缀 或不加前缀
        let has = item.findIndex((i: string) => {
          let isHas = content.indexOf(i) == 0 || content.indexOf('/' + i) == 0
          if (isHas) actionKeyWork = i
          return isHas
        }) > -1
        if (has) {
          hasKeyWork = key
          hasKeyWorkParams = content.split(actionKeyWork)[1]
          // 去除两端空格
          hasKeyWorkParams = hasKeyWorkParams.replace(/^\s*/g, "").replace(/\s*$/g, "")
        }
      }
    }
    if (hasKeyWork == 'changeUp') {
      const { upList, upId } = getConfig
      const upInfo = upList.find((item: any) => item.id == upId)
      if (hasKeyWorkParams) {
        console.log('hasKeyWorkParams',hasKeyWorkParams)
        const up = upList.find((item: any) => item.alias.find(i => i == hasKeyWorkParams))
        if (up) {
          updateConfig({
            upId: up.id,
            display: up.display || []
          })
          return session.send('爱丽丝充能完毕！已切换卡池喵\n当前up：' + up.name)
        }
        else {
          const result = [
            '暂时没有这个池子喵',
            `当前up：${upInfo.name}`,
            `可切换卡池：`,
          ]
          upList.map(i => {
            let name = i.name
            if (i.id == upId) name = i.name + '（当前）'
            result.push(name)
          })
          const text = result.join('\n')
          return session.send(text)
        }
      }
      else {
        const result = [
          `当前up：${upInfo.name}`,
          `可切换卡池：`,
        ]
        upList.map(i => {
          let name = i.name
          if (i.id == upId) name = i.name + '（当前）'
          result.push(name)
        })
        const text = result.join('\n')
        session.send(text)
      }
    }
    
  })
}
